import http from 'axios'
import { codeHandler } from 'services/Util'
import store from 'store'

// 测试服务器
// const URL = process.env.NODE_ENV === 'production'
//   ? 'https://dev-center.ishaohuo.cn/admin/index/index'
//   : '/admin/index/index'

// 正式服务器
const URL = process.env.NODE_ENV === 'production'
  ? 'https://center.ishaohuo.cn/admin/index/index'
  : '/admin/index/index'

/* 全局配置
-------------------------- */
function globalConfig () {
  // 如果access_token存在，在请求上带上access_token
  if (store.state.access_token) http.defaults.headers.access_token = store.state.access_token
  // 如果acc_id存在，在请求上带上acc_id
  // if (store.state.acc_id) http.defaults.headers.acc_id = store.state.acc_id
}

/* Get请求
-------------------------- */
async function Get ({ Copyright, Interface, Command }) {
  const headers = { copyright: Copyright, interface: Interface }
  const params = { command: Command }
  try {
    globalConfig()
    const res = await http.get(URL, { headers, params })
    if (String(res.data.code) === '000000') {
      return Promise.resolve([ null, res.data ])
    } else {
      return Promise.resolve([ new Error(res.data.msg) ])
    }
  } catch (e) {
    return Promise.resolve([ new Error('获取数据时出现了错误') ])
  }
}

/* Post请求
-------------------------- */
async function Post ({ Copyright, Interface, Command, Params = {} }) {
  const headers = { copyright: Copyright, interface: Interface }
  const metaParams = { command: Command, ...Params }
  console.log(metaParams)
  const params = { param: codeHandler.encode(JSON.stringify(metaParams), 'base64') }
  try {
    globalConfig()
    const res = await http.post(URL, params, { headers })
    if (String(res.data.code) === '000000') {
      store.commit('ToogleApiComplete')
      return Promise.resolve([ null, res.data.data ])
    } else {
      return Promise.resolve([ new Error(res.data.msg) ])
    }
  } catch (e) {
    return Promise.resolve([ new Error('获取数据时出现了错误') ])
  }
}

export {
  Post,
  Get
}
